/**
 * Created by zxx on 2016-4-12.
 */
/**
 * Description:该类主要用于创建一个开关控件
 * Copyright: 成都和为科技有限公司 2012
 *
 * 属性：
 *    state - 状态. 默认为fasle
 *    size - 控件大小 mini,small,normal,large  默认normal
 *    onColor - 打开颜色
 *    offColor - 关闭颜色
 *    onText - 打开文字
 *    offText - 关闭文字
 *    labelText - 开关按钮中间的Label文本
 *    handleWidth - 开关按钮左边和右边的宽度，单位像素
 *    labelWidth - 开关按钮Label文本的宽度，单位像素
 * 事件:
 *    stateChange - 改变状态回调
 */
function Switch() {
}

Switch.inherit(Control);

/**
 * 初始化方法
 */
Switch.prototype.init = function() {
    Switch.base.init.call(this);
}

/**
 * 创建HTML节点
 */
Switch.prototype.create = function() {
    this._html = $("<input type='checkbox'>");
}

Switch.prototype.initLoad = function() {
    if (!$().bootstrapSwitch) {
        //this.loadCSSFile("/public.common/webapi/common/switch/bootstrap-switch.css");
        this.loadScriptFile("/public.common/webapi/common/switch/bootstrap-switch.js");
    }
    this._state = false;
    var config = {};
    if (this.getAttribute().size) config.size = this.getAttribute().size;
    if (this.getAttribute().oncolor) config.onColor = this.getAttribute().oncolor;
    if (this.getAttribute().offcolor) config.offColor = this.getAttribute().offcolor;
    if (this.getAttribute().ontext) config.onText = this.getAttribute().ontext;
    if (this.getAttribute().offtext) config.offText = this.getAttribute().offtext;
    if (this.getAttribute().labeltext) config.labelText = this.getAttribute().labeltext;
    if (this.getAttribute().handlewidth) config.handleWidth = parseInt(this.getAttribute().handlewidth);
    if (this.getAttribute().labelwidth) config.labelWidth = parseInt(this.getAttribute().labelwidth);

    $(this._html).bootstrapSwitch(config);

    var state = this.getAttribute().state;
    if (state && state == "true") {
        this.setState(true);
    }

    //事件
    if (this.getAttribute().statechange) {
        var that = this;
        $(this._html).on('switchChange.bootstrapSwitch', function(event, state) {
            that.triggerAttributeEvent("statechange", state, event);
        });
    }
}

/**
 * 设置控件属性
 * @param name
 * @param value
 */
Switch.prototype.setControlAttr = function(name, value) {
    $(this._html).bootstrapSwitch(name, value, true);
}

/**
 * 动态改变状态
 */
Switch.prototype.setState = function(state) {
    this._state = state;
    $(this._html).bootstrapSwitch('state', state, true);
}

/**
 * 获得状态
 * @returns {*}
 */
Switch.prototype.getState = function() {
    return this._state;
}
